package com.s63.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.s63.entity.Dept;
import com.s63.mapper.DeptMapper;
import com.s63.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<Dept> list() {
        List<Dept> deptList;
        try {
            String json = stringRedisTemplate.opsForValue().get("s63:dept");
            if (StringUtils.hasText(json)) {
                deptList = objectMapper.readValue(json, List.class);
            } else {
                deptList = super.list();
                // 缓存到redis
                stringRedisTemplate.opsForValue().set("s63:dept", objectMapper.writeValueAsString(deptList));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return deptList;
    }
}
